package com.mz361.stdapi.controller;


import com.mz361.common.exception.ResultException;
import com.mz361.common.utils.EncryptUtil;
import com.mz361.common.utils.ResultVoUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.common.vo.ResultVo;
import com.mz361.component.jwt.annotation.IgnorePermissions;
import com.mz361.component.jwt.enums.JwtResultEnums;
import com.mz361.modules.system.domain.CMember;
import com.mz361.modules.system.domain.User;
import com.mz361.modules.system.service.CMemberService;
import com.mz361.modules.system.service.UserService;
import com.mz361.stdapi.service.SignInService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author niceale
 * @ date 2024/06/07
 */
@Api(tags = "注册登录相关接口")
@RestController
@Slf4j
public class SignInController {
    @Autowired
    private SignInService signInService;

    @Autowired
    private CMemberService cMemberService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "发送验证码", notes = "发送手机验证码，判断是否真实有效手机号")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
                    @ApiImplicitParam(name = "type", value = "短信类型，0:注册短信；1:登录短信；2:修改密码短信", dataType = "String", dataTypeClass = String.class, paramType = "query")})
    @IgnorePermissions
    @CrossOrigin
    @GetMapping("/api/v1/sendCode")
    public ResultVo sendCode(String phone, String type) {
        log.info("method【sendCode】：phone: {} type: {}", phone, type);
        boolean flag = signInService.sendCode(phone, type);
        if (flag) {
            return ResultVoUtil.success("发送成功！");
        } else {
            return ResultVoUtil.error("请勿重复发送！");
        }
    }

    @ApiOperation(value = "手机号校验", notes = "判断手机号是否申请过注册流程，0：新用户，1：已申请未完成注册，2：已完整注册流程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query")})
    @IgnorePermissions
    @CrossOrigin
    @GetMapping("/api/v1/verifyPhone")
    public ResultVo verifyPhone(String phone) {
        log.info("method【verifyPhone】：phone:{}", phone);
        String level = signInService.verifyPhone(phone);
        return ResultVoUtil.success("校验成功", level);
    }

    @ApiOperation(value = "验证码校验")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", dataTypeClass = String.class, paramType = "query")})
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/verify")
    public ResultVo verify(String phone, String code) {
        log.info("method【verify】：phone:{}, code = {}", phone, code);
        boolean flag = signInService.verify(phone, code,"0");
        if (flag) {
            return ResultVoUtil.success("校验成功");
        }
        return ResultVoUtil.error("校验失败");

    }

    @ApiOperation(value = "首次签注", notes = "点击下一步请求此接口，先进行手机验证码校验，成功后在进行首次注册流程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型 1:个人用户，2:企业用户 ", dataType = "String", dataTypeClass = String.class, paramType = "query")
    })
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/fistSingIn")
    public ResultVo fistSingIn(String phone, String code, String password, String type) {
        log.info("method【fistSingIn】：phone = {}, code = {}, password = {}, type = {}", phone, code, password, type);
        boolean flag = signInService.verify(phone, code,"0");
        if (flag) {
            CMember cMember = cMemberService.getByPhone(phone);
            if (cMember != null) {
                if (cMember.getType().equals("1")) {
                    return ResultVoUtil.error("已注册,请登录");
                }
                if (cMember.getCompany() != null) {
                    return ResultVoUtil.error("已认证,请登录");
                }
            } else {
                signInService.fistSingIn(phone, password, type);
            }
            return ResultVoUtil.success("成功");

        } else {
            return ResultVoUtil.error("手机验证码校验失败");
        }
    }

    @ApiOperation(value = "企业认证", notes = "企业自主认证信息，后台根据邀请码绑定推广业务员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "companyName", value = "公司名称", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "companyNum", value = "企业信用代码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", dataType = "String", dataTypeClass = String.class, paramType = "query")
    })
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/verifyCompany")
    public ResultVo verifyCompany(String phone, String companyName, String companyNum, String inviteCode) {
        log.info("method【verifyCompany】：phone = {}, companyName = {}, companyNum = {}, inviteCode = {}", phone, companyName, companyNum, inviteCode);
        User user;
        if (StringUtil.isEmpty(inviteCode)) {
            user = userService.getByName("15800000001");//绑定满智平台
        } else {
            user = signInService.getByInviteCode(inviteCode);
            if (user == null) {
                return ResultVoUtil.error("邀请码无效");
            }
        }

        String flag = signInService.verifyCompany(phone, companyName, companyNum, user);
        switch (flag) {
            case "1":
                return ResultVoUtil.error("此号" + phone + "未发现申请注册");
            case "2":
                return ResultVoUtil.error("此信用代码已注册");
            case "3":
                return ResultVoUtil.error("企业认证失败");
            case "4":
                return ResultVoUtil.error("企业信息错误");
            default:
                return ResultVoUtil.success("成功");
        }


    }

    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "loginType", value = "登录方式 0:手机密码登录,1:手机验证码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", dataTypeClass = String.class, paramType = "query")})
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/login")
    public ResultVo login(String phone, String loginType, String code, String password) {
        log.info("method【login】phone = {}, loginType = {}, code = {}, password = {}", phone, loginType, code, password);
        // 根据用户名获取系统用户数据
        CMember cMember = signInService.getByPhone(phone);
        if (cMember == null) {
            throw new ResultException(JwtResultEnums.AUTH_REQUEST_NULLUSERERROR);
        } else {
            if ("0".equals(loginType)) {
                // 对明文密码加密处理
                String encrypt = EncryptUtil.encrypt(password, cMember.getSalt());
                // 判断密码是否正确
                if (encrypt.equals(cMember.getPassword())) {
                    return ResultVoUtil.success("登录成功", signInService.getLoginData(phone, cMember));
                } else {
                    throw new ResultException(JwtResultEnums.AUTH_REQUEST_ERROR);
                }
            } else {
                boolean flag = signInService.verify(phone, code,"1");
                if (flag) {
                    return ResultVoUtil.success("登录成功", signInService.getLoginData(phone, cMember));
                }
                throw new ResultException(JwtResultEnums.AUTH_REQUEST_CODEERROR);
            }
        }
    }


    @ApiOperation(value = "退出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "渠道KEY"),
            @ApiImplicitParam(name = "timestamp", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "时间戳"),
            @ApiImplicitParam(name = "token", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "token", required = true),
            @ApiImplicitParam(name = "userId", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "用户ID", required = true)})
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/loginout")
    public ResultVo loginout(@RequestHeader String userId) {
        log.info("method【loginout】userId = {}", userId);
        // 根据用户名获取系统用户数据
        CMember cMember = signInService.getByUserId(userId);
        signInService.delMessge(cMember.getPhone());
        return ResultVoUtil.success("ok");
    }

    @ApiOperation(value = "找回密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", dataTypeClass = String.class, paramType = "query")})
    @IgnorePermissions
    @CrossOrigin
    @PostMapping("/api/v1/findPassword")
    public ResultVo findPassword(String phone, String code, String password) {
        boolean flag = signInService.verify(phone, code,"2");
        if (flag) {
            CMember cMember = signInService.findPassword(phone, password);
            if (null != cMember) {
                return ResultVoUtil.success("成功");
            } else {
                return ResultVoUtil.error("无此用户信息,请注册");
            }
        } else {
            return ResultVoUtil.error("手机验证码校验失败");
        }
    }

}
